﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.ServiceLocation;
using YoProgramo.Domain.BusinessLogic.Service;
using YoProgramo.Domain.Core.Interfaces;

namespace YoProgramo.Domain.BusinessLogic.Extensions
{
    public static class ExtraTools {
        public static string GenerateSlug(this HtmlHelper html, string phrase) {
            return GenerateSlug(phrase);
        }

        public static bool IsAuthor<T>(this HtmlHelper html, string username ,T obj)
            where T : class
        {
            IUserService service = ServiceLocator.Current.GetInstance<IUserService>();
            var user = service.GetByUserName(username);
            return ((IEntityCommon)obj).ByUser == user;
        }

        public static string GenerateSlug(string phrase) {
            string str = phrase.ToLower();

            str = str.Replace("#", "sharp");
            str = str.Replace("+", "plus");
            str = str.Replace("?", "ask");
            str = str.Replace("%", "um");
            str = str.Replace("&", "amp");
            str = str.Replace(".", "dot");
            str = str.Replace("$", "ss");
            str = str.Replace("<", "op");
            str = str.Replace(">", "cl");
            str = str.Replace("á", "a");
            str = str.Replace("é", "e");
            str = str.Replace("í", "i");
            str = str.Replace("ó", "o");
            str = str.Replace("ú", "u");

            str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); // caracteres no permitidos       
            str = Regex.Replace(str, @"\s+", " ").Trim(); // espacios en uno
            str = str.Substring(0, str.Length <= 55 ? str.Length : 55).Trim(); 
            str = Regex.Replace(str, @"\s", "-");

            return str;
        }

        public static string EncodeMD5(string originalPassword) {
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;
            
            md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
            encodedBytes = md5.ComputeHash(originalBytes);

            return BitConverter.ToString(encodedBytes);
        }

        public static string GetMailTemplateFolder() {
            return HttpContext.Current.Server.MapPath("/MailTemplates/");
        }


        //By Jeff Atwood
        //HTML http://refactormycode.com/codes/333-sanitize-html 
        //Start

        private static Regex _tags = new Regex("<[^>]*(>|$)",
                                               RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
        private static Regex _whitelist = new Regex(@"
            ^</?(b(lockquote)?|code|d(d|t|l|el)|em|h(1|2|3)|i|kbd|li|ol|p(re)?|s(ub|up|trong|trike)?|ul)>$|
            ^<(b|h)r\s?/?>$",
                                                    RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
        private static Regex _whitelist_a = new Regex(@"
            ^<a\s
            href=""(\#\d+|(https?|ftp)://[-a-z0-9+&@#/%?=~_|!:,.;\(\)]+)""
            (\stitle=""[^""<>]+"")?\s?>$|
            ^</a>$",
                                                      RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
        private static Regex _whitelist_img = new Regex(@"
            ^<img\s
            src=""https?://[-a-z0-9+&@#/%?=~_|!:,.;\(\)]+""
            (\swidth=""\d{1,3}"")?
            (\sheight=""\d{1,3}"")?
            (\salt=""[^""<>]*"")?
            (\stitle=""[^""<>]*"")?
            \s?/?>$",
                                                        RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);


        /// <summary>
        /// sanitize any potentially dangerous tags from the provided raw HTML input using 
        /// a whitelist based approach, leaving the "safe" HTML tags
        /// CODESNIPPET:4100A61A-1711-4366-B0B0-144D1179A937
        /// </summary>
        public static string Sanitize(string strhtml) {
            if (String.IsNullOrEmpty(strhtml)) return strhtml;

            string tagname;
            Match tag;

            // match every HTML tag in the input
            MatchCollection tags = _tags.Matches(strhtml);
            for (int i = tags.Count - 1; i > -1; i--) {
                tag = tags[i];
                tagname = tag.Value.ToLowerInvariant();

                if (!(_whitelist.IsMatch(tagname) || _whitelist_a.IsMatch(tagname) || _whitelist_img.IsMatch(tagname))) {
                    strhtml = strhtml.Remove(tag.Index, tag.Length);
                    //System.Diagnostics.Debug.WriteLine("tag sanitized: " + tagname);
                }
            }

            return strhtml;
        }

        //By Jeff Atwood
        //HTML http://refactormycode.com/codes/333-sanitize-html 
        //End

    }
}